package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// Cors 跨域中间件
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求方法和来源
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")

		// 如果请求来源不为空，设置跨域相关的响应头
		if origin != "" {
			// 允许所有来源访问
			c.Header("Access-Control-Allow-Origin", "*")
			// 允许的HTTP方法
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			// 允许的请求头
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			// 暴露的响应头
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			// 允许携带凭证
			c.Header("Access-Control-Allow-Credentials", "true")
		}

		// 如果是OPTIONS请求，直接返回204状态码，不继续处理
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		// 继续处理请求
		c.Next()
	}
}